package ro.gateway.aida.usr;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.utils.HttpUtils;
import ro.gateway.aida.utils.SysProp;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.ChangeLanguageServlet;


/**
 * <p>Title: Romanian AIDA</p>
 * <p>Description: :D application</p>
 * <p>Copyright: Copyright (comparator) 2003</p>
 * <p>Company: Romania Development Gateway </p>
 *
 * @author Mihai Popoaei, mihai_popoaei@yahoo.com, smike@intellisource.ro
 * @version 1.0-* @version $Id: LoginServlet.java,v 1.1 2004/10/24 23:37:05 mihaipostelnicu Exp $
 */
public class LoginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request,
					 HttpServletResponse response)
		  throws ServletException, IOException {

		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
					  HttpServletResponse response)
		  throws ServletException, IOException {

		ServletContext application = this.getServletContext();
		PersistenceToken token = PersistenceManager.tokenLookup(application);
		UserDB pers_man = UserDB.getManager(token);
		HttpSession session = request.getSession();

		String login = HttpUtils.getValidTrimedString(request, "login", null);
		String pass = HttpUtils.getValidTrimedString(request, "pass", null);
		if (login == null) {
			session.invalidate();
			request.getSession(true);

			response.sendRedirect(request.getContextPath() + "/");
			return;
		}

		User user = null;
		String pwdreset = "N";
		try {
			user = pers_man.getByLogin(login);
			if (user != null) {
				pwdreset = pers_man.getPWDReset(user.getId());
				if ("Y".equals(pwdreset)) {
					pers_man.setPWDReset("N", user.getId());
				}
				//WRI-style passwords 
				if (user.getPass() != null && user.getPass().startsWith("^^^")) {
					String passwd = user.getPass().substring(3);
					passwd = HttpUtils.getHash(passwd);
					user.setPass(passwd);
					UserDB.getManager(token).update(user);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (user == null) {
			request.setAttribute(PNAME_ERRORS, new String[]{"err.usrnf"});
			request.getRequestDispatcher(JSP_PAGE).
				  forward(request, response);
			return;
		}
		if (user == null || user.isStandby()) {
			if (user != null && user.isStandby()) {
				request.setAttribute(PNAME_ERRORS, new String[]{"err.usrdisabled"});
			} else {
				request.setAttribute(PNAME_ERRORS, new String[]{"err.usrnf"});
			}
			request.getRequestDispatcher(JSP_PAGE).
				  forward(request, response);
			return;
		}

		pass = HttpUtils.getHash(pass);
		if (((pass == null) && (user.getPass() == null)) ||
			  ((pass != null) && (pass.equals(user.getPass())))) {

			// iau refererul
			String referer = HttpUtils.getReferer(request, PNAME_REFERER, request.getContextPath() + "/admin.jsp", new String[]{"login"});

			// invalidez sesiunea
			session.invalidate();
			session = request.getSession(true);


			// pun userul gasit in bd
			session.setAttribute(UserConstants.LOGGED_USER, user);
			session.removeAttribute(PNAME_REFERER);

			//sets inactive time to 20 minutes
			session.setMaxInactiveInterval(60 * Integer.parseInt(Utils.getProperty(token, SysProp.SESSION_TIMEOUT)));

			// schimb limba curenta coresp. profilului
			ChangeLanguageServlet.
				  setWorkingLanguage(user.getWorkingLanguage(), session);

			// setez cukiz
			Cookie cuki = new Cookie(LAST_LG_TIME_COOKIE,
				  String.valueOf(System.currentTimeMillis()));
			cuki.setMaxAge(COOKIE_LIFETIME);
			response.addCookie(cuki);
			cuki = new Cookie(LAST_LG_USR_COOKIE,
				  user.getLogin());
			cuki.setMaxAge(COOKIE_LIFETIME);
			response.addCookie(cuki);

			// redirectez

			if ("Y".equals(pwdreset)) {
				response.sendRedirect(request.getContextPath() + "/usr/uedit?action=edit&id=" + user.getId());
				return;
			}

			response.sendRedirect(request.getContextPath() + "/");
			return;
		} else {
//                  System.out.println( "pass:" + user.getPass() );
//                  System.out.println( "typed pass:" + pass );
			request.setAttribute(PNAME_ERRORS, new String[]{"err.incpass"});
			request.getRequestDispatcher(JSP_PAGE).
				  forward(request, response);
			return;
		}
	}

	public static final String PNAME_ERRORS = "LOGIN_ERRORS";
	public static final String PNAME_REFERER = "LOGIN_REFERER";
	public static final String JSP_PAGE = "index.jsp";
	public static final String LAST_LG_USR_COOKIE = "lastlogin_usr";
	public static final String LAST_LG_TIME_COOKIE = "lastlogin_time";
	public static final int COOKIE_LIFETIME = 1000 * 3600 * 24 * 3;
}
